
#function to code variables to range from 0 to 1
zero1 <- function(x, minx=NA, maxx=NA){
  res <- NA
  if(is.na(minx)) res <- (x - min(x,na.rm=T))/(max(x,na.rm=T) -min(x,na.rm=T))
  if(!is.na(minx)) res <- (x - minx)/(maxx -minx)
  res
}

#function to install packages if they don't exist
ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg)) 
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

#Get odds ratios out of stargazer
stargazer2 <- function(model, odd.ratio = F, ...) {
  if(!("list" %in% class(model))) model <- list(model)
  
  if (odd.ratio) {
    coefOR2 <- lapply(model, function(x) exp(coef(x)))
    seOR2 <- lapply(model, function(x) exp(coef(x)) * summary(x)$coef[, 2])
    p2 <- lapply(model, function(x) summary(x)$coefficients[, 4])
    stargazer(model, coef = coefOR2, se = seOR2, p = p2, ...)
    
  } else {
    stargazer(model, ...)
  }
}

get_lower_tri<-function(cormat){
  cormat[lower.tri(cormat)] <- NA
  return(cormat)
}

super.cluster.fun<-function(model, cluster)
{
  require(multiwayvcov)
  require(lmtest)
  vcovCL<-cluster.vcov(model, cluster)
  
  assign("coef",coeftest(model, vcovCL),.GlobalEnv)
  #coef<-coeftest(model, vcovCL)
  w<-waldtest(model, vcov = vcovCL, test = "F")
  ci<-get_confint(model, vcovCL)
  
  return(list(coef, w, ci))
}

get_confint<-function(model, vcovCL){
  t<-qt(.975, model$df.residual)
  ct<-coeftest(model, vcovCL)
  est<-cbind(ct[,1], ct[,1]-t*ct[,2], ct[,1]+t*ct[,2])
  colnames(est)<-c("Estimate","LowerCI","UpperCI")
  return(est)
}

# usage
packages <- c("stringr", "haven", "readstata13", "foreign", "stargazer", "ggplot2", "lavaan", "dplyr", "data.table", "xtable", "nnet", "multiwayvcov", "interplot", "sjPlot", "effects", "miceadds")
ipak(packages)

#sink("sessionInfo.txt")
#sessionInfo()
#sink()



# data_summary <- function(x) {
#   m <- mean(x)
#   ymin <- m-sd(x)
#   ymax <- m+sd(x)
#   return(c(y=m,ymin=ymin,ymax=ymax))
# }
# 
# 
# 
# #Order correlation matrix
# reorder_cormat <- function(cormat){
#   # Use correlation between variables as distance
#   dd <- as.dist((1-cormat)/2)
#   hc <- hclust(dd)
#   cormat <-cormat[hc$order, hc$order]
# }
# 
# 
# 
# median.split <- function(var){
#   ifelse(var>median(var, na.rm=T), 1,0)
# }
# 
# sign.root <- function(var){
#   sign(var)*sqrt(abs(var))
# }
# 
# get.desc <- function(var){
#   summary <- c(psych::alpha(var, check.keys = TRUE)$total$raw_alpha,
#       mean(zero1(apply(var,1,sum)),na.rm=T),
#       sd(zero1(apply(var,1,sum)),na.rm=T),
#       min(zero1(apply(var,1,sum)),na.rm=T),
#       max(zero1(apply(var,1,sum)),na.rm=T))
#   output <- paste0("alpha=",round(summary[1],2),", M=",round(summary[2],2), ", SD=", round(summary[3],2), ", Min=",round(summary[4],0), ", Max=", round(summary[5],0))
#   return(output)
# }
# 


